

package main

import (
	"fmt"
	"io/ioutil"
	v1 "k8s.io/api/core/v1"
	meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/informers"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/cache"
	"k8s.io/client-go/tools/clientcmd"
	"log"
)

//初始化k8s客户端
func GetK8sClient() (clientset *kubernetes.Clientset, err error) {
	var (
		restConf *rest.Config
	)

	if restConf, err = getRestConf(); err != nil {
		return
	}

	//生成client配置
	if clientset, err = kubernetes.NewForConfig(restConf); err != nil {
		goto END
	}
END:
	return
}

// 获取k8s restful client配置
func getRestConf() (restConf *rest.Config, err error) {
	var (
		kubeconfig []byte
	)

	// 读kubeconfig文件
	if kubeconfig, err = ioutil.ReadFile("./conf/config.yml"); err != nil {
		goto END
	}

	// 生成rest client配置
	if restConf, err = clientcmd.RESTConfigFromKubeConfig(kubeconfig); err != nil {
		goto END
	}

END:
	return
}

// 获取podList
func InitPods() {
	client , err := GetK8sClient()
	if err != nil {
		log.Printf("链接k8s失败！%s", err)
	}
	stopCh := make(chan struct{})
	defer close(stopCh)

	//表示每分钟进行一次resync，resync会周期性地执行List操作
	sharedInformers := informers.NewSharedInformerFactory(client, 0)

	informer := sharedInformers.Core().V1().Pods().Informer()

	informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc: func(obj interface{}) {
			pods := obj.(*v1.Pod)
			fmt.Println(len(pods.Status.ContainerStatuses))
			for i :=0; i < len(pods.Status.ContainerStatuses);i ++ {
				fmt.Println(pods.Name,pods.Status.ContainerStatuses[i].Ready)
			}
		},
		UpdateFunc: func(oldObj, newObj interface{}) {
			oObj := oldObj.(meta_v1.Object)
			nObj := newObj.(meta_v1.Object)
			log.Printf("%s Pod Updated to %s", oObj.GetName(), nObj.GetName())
		},
		DeleteFunc: func(obj interface{}) {
			mObj := obj.(meta_v1.Object)
			log.Printf("Pod Deleted from Store: %s", mObj.GetName())
		},
	})

	informer.Run(stopCh)
}


func main() {
	InitPods()

}